<template>
  <div class="elm-counter">
    <img v-if="value!=0" class="icon-add-sub"
      src="../../../images/icon-sub.png" 
      @click="sub"
    >
    <span v-if="value!=0" class="elm-counter-value">{{value}}</span>
    <span v-if="specProducts.length" class="spec-btn"
      @click="handleSpecsDialogOpen"
    >选规格</span>
    <img v-else src="../../../images/icon-add.png"  
      ref="addIconRef"
      class="icon-add-sub"
      @click="add"  
    >
  </div>
</template>
<script>
import {ADD_PRODUCT,REMOVE_PRODUCT} from '../../../store/mutationTypes'
import {mapState,mapActions} from 'vuex'
export default {
  model:{
    prop:'value',
    event:'updateValue' //相当于声明value来接受v-model的值，同时监听'updateValue'事件修改value的值
  },
  props:{
    // 数量
    value: 0,
    restaurant_id:0,
    category_id:0,
    item_id:0,
    // 商品规格列表
    specifications:{
      type: Object,
      default: ()=>{}
    },
    // 不同规格商品列表
    specProducts:{
      type: Array,
      default:()=>[]
    },
    // 商品信息
    product:{
      type:Object,
      default:()=>{}
    },
    // 是否监听变化，是否开启@onChange
    listenOnChange:{
      type: Boolean,
      default: false
    }
    
  },
  data(){
    return{
      
    }
  },
  computed:{
    ...mapState('cart',['shopcarts']),
    curCategory(){
      const shopcart = this.shopcarts[this.restaurant_id]
      if(shopcart){
        const category = shopcart[this.category_id]
        if(category)
          return category
      }
      return {}
    }
  },
  methods:{
    // 映射actions
    //相当于：this.$store.dispatch('cart/addProduct',this.product)
    ...mapActions('cart',[ADD_PRODUCT,REMOVE_PRODUCT]), 

    // +1
    add(){
      this.addToCart(this.product)
      //加到购物车事件
      const {x, y} = this.$refs.addIconRef.getBoundingClientRect()
      // console.log(this.$refs.addIconRef.getBoundingClientRect());
      this.$emit('afterAddToCart',{x,y})
    },
    // -1
    sub(){
      // 如果是多规格商品，不允许点击“-”图标删除
      if(this.specProducts.length){
        this.$toast('多规格商品只能去购物车删除哦');
        return
      }
      this.rmFromCart(this.product)
    },

    // 从购物车删除
    rmFromCart({food_id, item_id, name, packing_fee, price, sku_id, stock, specs}){
      if(this.value <= 0)
        return
      const val = this.curCategory[food_id].quantity - 1
      this.$emit('updateValue', this.value - 1)

      // 是否监听onChange事件
      if(this.listenOnChange){  
        this.$emit('onChange', {
          restaurant_id: this.restaurant_id,
          category_id: this.category_id,
          item_id,
          food_id,
          type:'remove' // [add,remove,clear]
        })
      }

      // 移除商品
      this[REMOVE_PRODUCT]({
        restaurant_id: this.restaurant_id,
        category_id: this.category_id,
        geohash: '',
        // 购物车数据
        item_id,
        food_id,  //食品id,
        name,   //食品名称,
        packing_fee,//打包费,
        price,    //价格,
        sku_id,   //规格id,
        specs,    // 规格,
        stock,     //存量,
        quantity: val, //数量,
      })
    },

    // 添加到购物车
    addToCart ({food_id, item_id, name, packing_fee, price, sku_id, stock, specs}){
      const val = this.curCategory[food_id] ? this.curCategory[food_id].quantity+1 : 1
      this.$emit('updateValue', this.value + 1)
      // 是否监听onChange事件
      if(this.listenOnChange){  
        let add_car_count = 1
        Object.keys(this.curCategory).forEach(food_id=>{
          const food = this.curCategory[food_id]
          if(food.item_id == this.item_id){
            add_car_count += this.curCategory[food_id].quantity //累计之前数量
          }
        })
        this.$emit('onChange', {
          restaurant_id: this.restaurant_id,
          category_id: this.category_id,
          item_id,
          food_id,
          type:'add', // [add,remove,clear]
          add_car_count,
        })
      }
      
      // 添加商品
      this[ADD_PRODUCT]({
        restaurant_id: this.restaurant_id,
        category_id: this.category_id,
        geohash: '',
        // 购物车数据
        item_id,
        food_id,  //食品id,
        name,   //食品名称,
        packing_fee,//打包费,
        price,    //价格,
        sku_id,   //规格id,
        specs,    // 规格,
        stock,     //存量,
        quantity: val, //数量,
      })
    },

    // 选择商品规格
    handleSpecsDialogOpen(){
      this.$emit('onSelectSpecs', {
        specifications:this.specifications,
        specProducts:this.specProducts
      },this.addToCart)
    }
  }
}
</script>
<style lang='scss' scoped>
@import '../../../styles/var.scss';
.elm-counter{
  display: inline-block;
  height: .22rem;  //一定要设置固定高度，否则这个会引起shopFoods页面首次获取列表元素高度有较大误差
  overflow-y: hidden;
  position: relative;
  .icon-add-sub{
    width: .22rem;
    height: auto;
    vertical-align: middle;
  }
  
  .elm-counter-value{
    display: inline-block;
    height: .22rem;
    line-height: .22rem;
    margin: 0 .06rem;
    vertical-align: middle;
  }
  .spec-btn{
    display: inline-block;
    height: .22rem;
    line-height: .22rem;
    text-align: center;
    padding: 0 .06rem;
    font-size: .12rem;
    color: #FFF;
    background: $primary;
    border-radius: .05rem;
  }
}
</style>